import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import * as jwt from 'jsonwebtoken';
import { GqlExecutionContext } from '@nestjs/graphql';

export const jwtKey = '123456';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
    const ctx = GqlExecutionContext.create(context);
    const request = ctx.getContext().req;
    const jwtInput = request.headers.authorization;
    let decoded: { _id: string } | any;
    try {
      decoded = jwt.verify(jwtInput, jwtKey);
    } catch (err) {
      decoded = { _id: '' };
    }

    request.user = {
      _id: decoded?._id ?? '',
    };
    return true;
  }
}
